package com.basic.library.view.recyclerview

import android.os.SystemClock
import android.view.MotionEvent
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView


/**
 * @author yj
 * @description
 */
class RecyclerViewUtil(private val rcv: RecyclerView) {

    private var lastOffset: Int = 0
    private var lastPosition: Int = 0

    //监听RecyclerView滚动状态
    init {
        rcv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                if (recyclerView.layoutManager != null) {
                    getPositionAndOffset()
                }
            }
        })
    }

    /**
     * 记录RecyclerView当前位置
     */
    private fun getPositionAndOffset() {
        val layoutManager = rcv.layoutManager as LinearLayoutManager
        //获取可视的第一个view
        val topView = layoutManager.getChildAt(0)
        if (topView != null) {
            //获取与该view的顶部的偏移量
            lastOffset = topView.top
            //得到该View的数组位置
            lastPosition = layoutManager.getPosition(topView)
        }
    }

    /**
     * 让RecyclerView滚动到指定位置
     */
    fun scrollToPosition() {
        if (rcv.layoutManager != null && lastPosition >= 0) {
            (rcv.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(lastPosition, lastOffset)
        }
    }
}

//强制停止RecyclerView滑动方法
fun forceStopRecyclerViewScroll(mRecyclerView: RecyclerView) {
    mRecyclerView.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_CANCEL, 0f, 0f, 0))
}